package io.p2p.stream.dispatch.task;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.dispatch.model.ClientSharedModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainServerHeartbeatTask implements Runnable  {
    private static final Logger log = LoggerFactory.getLogger(MainServerHeartbeatTask.class);
    private String senderName;
    private String targetHost;
    private int targetPort;
    private Channel channel;

    public MainServerHeartbeatTask(String senderName, String targetHost,
                                   int targetPort,Channel channel){
        log.info("Enable Heartbeat Monitoring with the Main Service on ip: {},port:{}"
                ,targetHost,targetPort);
        this.targetHost = targetHost;
        this.targetPort = targetPort;
        this.senderName = senderName;
        this.channel = channel;
    }

    @Override
    public void run() {
        //发送心跳指令给main服务
        JSONObject heartbeatMsg = new JSONObject();
        heartbeatMsg.put("name", ClientSharedModel.loginName);
        heartbeatMsg.put("type","mainlineHeartbeat");
        heartbeatMsg.put("time",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        heartbeatMsg.put("msg","Mainline UDP Client Service heartbeat message.");

        log.info("Send to Main UDP Server Heartbeat: {}",heartbeatMsg);

        channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                heartbeatMsg.toJSONString(), StandardCharsets.UTF_8),new InetSocketAddress(targetHost,targetPort)));
    }
}
